//引入工具模板
const Koa = require('koa');
const app = new Koa();
const router = require('koa-router')();
const bodyparser = require("koa-bodyparser")
const cors = require('koa-cors')

const { Sequelize, Op, DataTypes } = require('sequelize');
//数据库
const sequelize = new Sequelize('ClassicDb', 'sa', '123456', {
    host: 'localhost',
    dialect: 'mssql'
})

let Blog = sequelize.define('blog', {
    tite: {
        type: DataTypes.STRING,
        allowNull: false
    },
    imports: {
        type: DataTypes.STRING,
        allowNull: false
    },
    text: {
        type: DataTypes.STRING,
        allowNull: false
    }
});



//查找和展示数据
router.get('/blog', async(ctx, next) => {
        let keyword = ctx.request.query.obj;
        console.log(keyword);
        let { pageIndex, pageSize } = ctx.request.query
        console.log(pageIndex, pageSize);

        let Findobj = await Blog.findAndCountAll({
            offset: (pageIndex - 1) * parseInt(pageSize), //从offset+1往后取limit条
            limit: parseInt(pageSize)
                // where:{}
        })
        console.log(Findobj);

        if (keyword != '') {
            ctx.body = await Blog.findAll({
                where: {
                    [Op.or]: [
                        { id: isNaN(keyword) ? -1 : parseInt(keyword) },
                        {
                            tite: {
                                [Op.like]: '%' + keyword + '%'
                            }
                        },
                        {
                            imports: {
                                [Op.like]: '%' + keyword + '%'
                            }
                        },
                        {
                            text: {
                                [Op.like]: '%' + keyword + '%'
                            }
                        }
                    ]
                },
                order: ['id']
            })
        } else {
            ctx.body = await Blog.findAll({ order: ['id'] })
        }
    })
    //删除
    .delete('/blog', async(ctx, next) => {
        let id = ctx.request.body.obj;
        await Blog.destroy({ where: { id: id } })
        ctx.body = await Blog.findAll({ order: ['id'] });
    })
    //修改
    .put('/blog', async(ctx, next) => {
        let obj = ctx.request.body;
        if (obj.id) {
            await Blog.update(obj, { where: { id: obj.id } })
            ctx.body = await Blog.findAll({ order: ['id'] });
        }
    })
    //添加
    .post('/blog', async(ctx, next) => {
        let obj = ctx.request.body;
        await Blog.create(obj)
        ctx.body = await Blog.findAll({ order: ['id'] });
    })

//挂载工具
app.use(cors());
app.use(bodyparser())
app.use(router.routes())

//监听
app.listen(8000, () => {
    console.log(`http://localhost:8000`);
})